from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework import mixins, status, request
from rest_framework import viewsets
from rest_framework.decorators import action

from drf_yasg.utils import swagger_auto_schema

from api.utils.common import with_common_response
from django.db.models import ObjectDoesNotExist
from api.models.user import User

from api.utils.common.db import paginate_list
from api.exceptions import ResourceNotFound
from api.auth import JWTAuthentication


from .serializer import (
    ProductBodySerializer,
    ProductImageBodySerializer,
    ProductQuerySerializer,
    ProductImageUpdateSerializer,
    PorductDataSerializer,
    ProductPutSerializer,
    ProductIdSerializer,
    AdminProductQuerySerializer,
    AdminProductImageQeurySerializer,
    AdminProductImageIDSerializer,
)
from ...models import Porduct, StockRecord, StockPrice, PorductImage


class ProductVeiwSet(viewsets.ViewSet):
    permission_classes = [JWTAuthentication]

    @swagger_auto_schema(
        operation_summary="商品列表",
        operation_description="商品列表",
        query_serializer=ProductQuerySerializer,
        responses=with_common_response({status.HTTP_200_OK: ProductBodySerializer}),
    )
    def list(self, request):
        serializer = ProductQuerySerializer(data=request.GET)
        if serializer.is_valid(raise_exception=True):
            product_id = serializer.validated_data.get("product_id")
            title = serializer.validated_data.get("title")
            businss_id = serializer.validated_data.get("businss_id")
            is_public = serializer.validated_data.get("is_public")
            per_page = serializer.validated_data.get("per_page")
            page = serializer.validated_data.get("page")
            limit = serializer.validated_data.get("limit")

            qeury_dict = {"deleted": False}
            if product_id:
                qeury_dict.update({"product_id": product_id})
            if title:
                qeury_dict.update({"title__icontains": title})
            if businss_id:
                qeury_dict.update({"businss_id": businss_id})
            if is_public:
                qeury_dict.update({"is_public": is_public})

            products = Porduct.objects.filter(**qeury_dict)
            data, total = paginate_list(products, page, per_page, limit)
            response = ProductBodySerializer({"total": total, "data": data})

            return Response(status=status.HTTP_200_OK, data=response.data)

    @swagger_auto_schema(
        operation_summary="商品详情",
        operation_description="商品详情",
        responses=with_common_response({status.HTTP_200_OK: PorductDataSerializer}),
    )
    def retrieve(self, request, pk):
        try:
            product = Porduct.objects.get(product_id=pk)
        except ObjectDoesNotExist as e:
            raise ResourceNotFound(detail="未找到商品")

        response = PorductDataSerializer(product)

        return Response(status=status.HTTP_200_OK, data=response.data)


class AdminProductVeiwSet(viewsets.ViewSet):
    permission_classes = [JWTAuthentication]

    @swagger_auto_schema(
        operation_summary="商品操作",
        operation_description="商品操作",
        request_body=AdminProductQuerySerializer,
        responses=with_common_response({status.HTTP_201_CREATED: ProductIdSerializer}),
    )
    def create(self, request):
        serializer = AdminProductQuerySerializer(data=request.data)
        if serializer.is_valid(raise_exception=True):
            product_id = serializer.validated_data.get("product_id")
            title = serializer.validated_data.get("title")
            businss_id = serializer.validated_data.get("businss_id")
            description = serializer.validated_data.get("description")
            is_public = serializer.validated_data.get("is_public")
            num_in_stock = serializer.validated_data.get("num_in_stock")
            pay_type = serializer.validated_data.get("pay_type")
            price = serializer.validated_data.get("price")

            product_fields = {}
            if title:
                product_fields.update({"title": title})
            if businss_id:
                product_fields.update({"businss_id": businss_id})
            if description:
                product_fields.update({"description": description})
            if is_public is not None:
                product_fields.update({"is_public": is_public})

            # 更新或创建商品
            product, _ = Porduct.objects.update_or_create(
                product_id=product_id, defaults=product_fields
            )

            if not product:
                raise ResourceNotFound(detail="产品更新或创建失败")

            # 更新或创建库存
            stock_record, _ = StockRecord.objects.update_or_create(
                product=product, defaults={"num_in_stock": num_in_stock}
            )

            if not stock_record:
                raise ResourceNotFound(detail="库存更新或创建失败")

            # 更新或创建库存价格

            stock_price, _ = StockPrice.objects.update_or_create(
                stock_record=stock_record, defaults={"type": pay_type, "price": price}
            )

            if not stock_price:
                raise ResourceNotFound(detail="库存价格更新创建失败")

            response = ProductIdSerializer(product)
            return Response(status=status.HTTP_201_CREATED, data=response.data)

    @swagger_auto_schema(
        operation_summary="删除商品",
        operation_description="删除商品",
        responses=with_common_response({status.HTTP_204_NO_CONTENT: ProductIdSerializer}),
    )
    def destroy(self, request, pk):
        try:
            product = Porduct.objects.get(product_id=pk)
        except ObjectDoesNotExist as e:
            raise ResourceNotFound(detail="未找到商品")

        product.deleted = True
        product.save()
        response = ProductIdSerializer(product)

        return Response(status=status.HTTP_204_NO_CONTENT, data=response.data)

    @swagger_auto_schema(
        operation_summary="上传图片",
        operation_description="上传图片",
        request_body=AdminProductImageQeurySerializer,
        responses=with_common_response({status.HTTP_202_ACCEPTED: AdminProductImageIDSerializer}),
    )
    @action(methods=["POST"], url_path="images", url_name="images", detail=False)
    def update_file(self, request):
        serializer = AdminProductImageQeurySerializer(data=request.data)
        if serializer.is_valid(raise_exception=True):
            purpose = serializer.validated_data.get("purpose")
            file_name = serializer.validated_data.get("file")
            file_type = serializer.validated_data.get("type")
            product_id = serializer.validated_data.get("product_id")

            try:
                product = Porduct.objects.get(product_id=product_id)
            except ObjectDoesNotExist:
                raise ResourceNotFound(detail="未找到商品")

            product_image = PorductImage.objects.create(
                product=product, type=file_type, file=file_name, purpose=purpose
            )

            response = AdminProductImageIDSerializer(product_image)

            return Response(status=status.HTTP_201_CREATED, data=response.data)
